﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Microsoft.SharePoint.Client
{

    public static class CamlExtensions
    {

        public static CamlOrderings GetOrderings(this CamlQuery query)
        {
            return new CamlOrderings(query.ViewXml);
        }
            
    }

    public class CamlOrderings : List<KeyValuePair<string, CamlOrderings.Direction>>
    {

        public CamlOrderings(string camlQueryString)
        {
            string ord = camlQueryString;
            ord = ord.Substring(ord.IndexOf("<OrderBy>"));
            ord = ord.Substring(0, ord.IndexOf("</OrderBy>") + 10);

            XDocument xDoc = XDocument.Parse(ord);

            foreach (var e in xDoc.Root.Elements("FieldRef"))
            {
                var aName = e.Attribute("Name");
                var aAsc = e.Attribute("Ascending");
                Add(new KeyValuePair<string, Direction>(aName.Value, aAsc != null ? ParseDirection(aAsc.Value) : Direction.Ascending));
            }
        }

        public bool ContainsField(string fieldRef)
        {
            return this.Any(x => x.Key == fieldRef);
        }

        public KeyValuePair<string, CamlOrderings.Direction> this[string fieldRef]
        {
            get
            {
                return FirstOrDefault(fieldRef);
            }
        }

        public KeyValuePair<string, CamlOrderings.Direction> FirstOrDefault(string fieldRef)
        {
            return this.FirstOrDefault(x => x.Key == fieldRef);
        }
        
        public int IndexOf(string fieldRef)
        {
            KeyValuePair<string, CamlOrderings.Direction> kvp = FirstOrDefault(fieldRef);
            if (kvp.Equals(default(KeyValuePair<string, Direction>)))
            {
                return -1;
            }
            return this.IndexOf(kvp);
        }

        private static Direction ParseDirection(string ascending)
        {
            if (string.IsNullOrEmpty(ascending))
            {
                return Direction.None;
            }
            if (bool.Parse(ascending))
            {
                return Direction.Ascending;
            }
            return Direction.Descending;
        }

        public enum Direction
        {
            None = 0,
            Ascending = 1,
            Descending = 2
        }

    }

}